package org.joe.chinachess.core.rules;

import org.joe.chinachess.core.ChessBoard;
import org.joe.chinachess.core.po.Chess;
import org.joe.chinachess.utils.Constants;
import org.joe.chinachess.utils.Point;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 炮的行棋规则
 *
 * @author Joe
 */
public class PaoRule implements ChessRule {


    @Override
    public boolean isCanEat(Point startPoint, Point endPoint, ChessBoard chessboard) throws Exception {
        Map<Point, Chess> pointChessMap = chessboard.getPointChessMap();
        if (startPoint == null || endPoint == null) {
            return false;
        }
        Chess start = pointChessMap.get(startPoint);
        Chess target = pointChessMap.get(endPoint);
        if (start == null || target == null) {
            return false;
        }
        if (target.getState() != Constants.Status.UNKNOW && start.getColor() == target.getColor()) {
            return false;
        }

        //如果x轴一样，则纵向比较
        if (startPoint.getX() == endPoint.getX()) {
            int i = startPoint.getY() - endPoint.getY();
            if (i > 1) {
                return countYSize(endPoint, startPoint, pointChessMap);
            } else if (i < -1) {
                return countYSize(startPoint, endPoint, pointChessMap);
            } else {
                return false;
            }
        }
        if (startPoint.getY() == endPoint.getY()) {
            int i = startPoint.getX() - endPoint.getX();
            if (i > 2) {
                return countXSize(endPoint, startPoint, pointChessMap);
            } else if (i < -2) {
                return countXSize(startPoint, endPoint, pointChessMap);
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean isCanMove(Point source, Point dest, ChessBoard chessboard) throws Exception {
        return false;
    }

    private boolean countXSize(Point minPoint, Point maxPoint, Map<Point, Chess> pointChessMap) {
        List<Chess> chessList = new ArrayList<>();
        for (int m = minPoint.getX() + 1; m < maxPoint.getX(); m++) {
            Chess e = pointChessMap.get(new Point(m, minPoint.getY()));
            if (e != null) {
                chessList.add(e);
            }
        }
        if (chessList.size() == 1) {
            return true;
        } else {
            return false;
        }
    }

    private boolean countYSize(Point minPoint, Point maxPoint, Map<Point, Chess> pointChessMap) {
        List<Chess> chessList = new ArrayList<>();
        for (int m = minPoint.getY() + 1; m < maxPoint.getY(); m++) {
            Chess e = pointChessMap.get(new Point(minPoint.getX(), m));
            if (e != null) {
                chessList.add(e);
            }
        }
        if (chessList.size() == 1) {
            return true;
        } else {
            return false;
        }
    }
}
